package com.nulldev.util.crypto.encryptAPI;

import java.nio.charset.Charset;

import com.nulldev.util.crypto.encryptAPI.manage.Encryptor;
import com.nulldev.util.encoding.base64.Base64;

/**
 * Port from EncryptUtil.API_V3
 */
public class XOR extends Encryptor {

    private static byte[] xorWithKey(byte[] a, byte[] key) {
        byte[] out = new byte[a.length];
        for (int i = 0; i < a.length; i++) {
            out[i] = (byte) (a[i] ^ key[i%key.length]);
        }
        return out;
    }

    private static byte[] base64Decode(final String s) {
    	return Base64.decodeBase64(s);
    }

    private static String base64Encode(final byte[] bytes) {
    	return Base64.encodeBase64String(bytes);
    }

	@Override
	public String getEncryptorID() {
		return "encryptAPI.XOR";
	}

	@Override
	public String[] supportedEncryptors() {
		return new String[] {"XOR"};
	}

	@Override
	public String encrypt(String text, String password) {
		return base64Encode(xorWithKey(text.getBytes(), password.getBytes()));
	}

	@Override
	public String decrypt(String text, String password) {
		return new String(xorWithKey(base64Decode(text), password.getBytes()));
	}

	@Override
	public byte[] encryptBytes(byte[] data, String password) {
		return xorWithKey(data, password.getBytes());
	}

	@Override
	public byte[] decryptBytes(byte[] data, String password) {
		return xorWithKey(data, password.getBytes());
	}
}
